import {Image, StyleSheet, View, Text, TouchableOpacity, ScrollView, Dimensions} from 'react-native';
import {Stack, useRouter} from "expo-router";
import { scaleSize } from "@/utils/screenSize"
import AntDesign from '@expo/vector-icons/AntDesign';
import { Ionicons } from '@expo/vector-icons';
import {useEffect, useState, useRef} from "react";
import NavBack from "@/components/navBack";
import * as React from "react";
import MapView, { Marker } from 'react-native-maps';
import locationIcon from '@/assets/images/space/locationIcon.png';
import Carousel from 'react-native-reanimated-carousel';
import { getSpaceMapListByRequest } from "@/services/spaceServices"
import {useSelector} from "react-redux";
import {RootState} from "@/store";
import {WebView} from "react-native-webview";
const mapIcon = require("@/assets/images/space/mapIcon.png")


export default function spaceIndexScreen() {

    const [list, setList] = useState([]);
    const [lt, setLt] = useState("");
    const [lg, setLg] = useState("");
    const [locationList, setLocationList] = useState([]);

    const login = useSelector((state: RootState) => state.login);
    const webviewRef = React.useRef(null);

    const router = useRouter();
    const touchStartX = useRef(0); // 记录触摸起点 X 坐标
    const touchStartY = useRef(0); // 记录触摸起点 Y 坐标
    const isSliding = useRef(false); // 是否在滑动中


    useEffect(() => {
        getList();
    }, []);

    const getList = function () {
        const data = {
            province: login?.locationInfo?.province || "",
            city: login?.locationInfo?.city || ""
        };
        getSpaceMapListByRequest(data)
            .then(res => {
                let tempList = []
                if (res.data.items && res.data.items.length > 0) {
                  try {
                      tempList = res.data.items.map(function (item, index) {
                          console.log('item', item);  // 调试输出item
                          const tempLocation = item?.addressBackup?.data?.[0]?.location;
                          if (!tempLocation) {
                              console.log('Invalid location for item', item);
                          }
                          const obk = {
                              id: index,
                              lat: Number(tempLocation?.lat) || "",
                              lng: Number(tempLocation?.lng) || "",
                              title: "1",
                          };
                          console.log('obk', obk);
                          return obk;
                      });
                  } catch (err) {
                      console.log('err', err)
                  };
                    console.log('geometriesList', tempList);
                } else {
                    console.log('res.data.items is empty or undefined');
                }
                setLocationList(tempList);

                setList(res.data.items);
                const currentItems = res.data.items;
                if (currentItems.length > 0) {
                    currentItems.forEach((item: any, index: number) => {
                        if (!lg || !lt) {
                            const location = res?.data?.items[0]?.addressBackup?.data[0]?.location;
                            setLt(location?.lat);
                            setLg(location?.lng);
                        };
                    })
                } else {
                    setLt(login?.locationInfo.location.lat);
                    setLg(login?.locationInfo.location.lng);
                };

                console.log('getSpaceMapListByRequest', );
            })
            .catch(err => {
                console.log("")
            })
    };

    const width = Dimensions.get('window').width;

    const handleResponderMove = (e) => {
        const currentX = e.nativeEvent.pageX;
        const currentY = e.nativeEvent.pageY;

        const deltaX = Math.abs(currentX - touchStartX.current);
        const deltaY = Math.abs(currentY - touchStartY.current);

        // 如果滑动距离超过阈值（横向或纵向），标记为滑动
        if (deltaX > 10 || deltaY > 10) {
            isSliding.current = true;
        }
    };

    const handleResponderRelease = (e, item) => {
        // 如果未检测到滑动，判定为点击
        if (!isSliding.current) {
            // router.push("/activityDetail/")
        } else {
            // console.log('item', item.addressBackup.data[0])
            console.log('Ignored: Swipe detected');
            cutMap(item)
        }
        isSliding.current = false; // 重置滑动状态
    };

    const cutMap = function (item) {
        if (item?.addressBackup?.data && item?.addressBackup?.data.length > 0) {
            const location = item?.addressBackup?.data[0]?.location;
            console.log('location', location);
            if (location) {
                setLt(location?.lat);
                setLg(location?.lng);
                webviewRef.current?.postMessage(JSON.stringify({ lat: location.lat, lng: location.lng }));
            };

        };

    };

    const searchMethod = function () {
        console.log("hello")
    };

    const html = `
    <!DOCTYPE html>
    <html>
    <head>
      <meta charset="utf-8" />
      <meta name="viewport" content="width=device-width, initial-scale=1" />
      <script src="https://map.qq.com/api/gljs?v=1.exp&key=VS6BZ-V2CCG-WVAQL-QM2WG-AMJIE-NOF3Q"></script>
      <style>
        body, html { margin: 0; padding: 0; height: 100%; width: 100%; }
        #map { width: 100%; height: 100%; }
      </style>
    </head>
    <body>
      <div id="map"></div>
      <script>
        var markersData = ${JSON.stringify(locationList)};

        var map = new TMap.Map('map', {
          center: new TMap.LatLng(markersData[0].lat, markersData[0].lng), 
          zoom: 14
        });

        var markerLayer = new TMap.MultiMarker({
          id: 'marker-layer',
          map: map,
          styles: {
            marker: new TMap.MarkerStyle({
              width: 25,
              height: 35,
              anchor: { x: 16, y: 32 },
              src: 'https://mapapi.qq.com/web/lbs/javascriptGL/demo/img/markerDefault.png'
            })
          },
          geometries: markersData.map(marker => ({
            id: marker.id,
            styleId: 'marker',
            position: new TMap.LatLng(marker.lat, marker.lng),
            properties: { title: marker.title }
          }))
        });

        window.updateMarkers = function(newMarkers) {
          if (newMarkers.length === 0) return;

          var firstMarker = newMarkers[0];
          map.panTo(new TMap.LatLng(firstMarker.lat, firstMarker.lng));

          markerLayer.setGeometries(newMarkers.map(marker => ({
            id: marker.id,
            styleId: 'marker',
            position: new TMap.LatLng(marker.lat, marker.lng),
            properties: { title: marker.title }
          })));
        };
        
         window.updateMap = function(lat, lng) {
          var newCenter = new TMap.LatLng(lat, lng);
          map.panTo(newCenter); // 刷新地图中心位置
        };


        // 监听 React Native 发送的新标记点数据
        window.addEventListener('message', function(event) {
          var data = JSON.parse(event.data);
          window.updateMap(data.lat, data.lng);
          if (data.markers) {
            window.updateMarkers(data.markers);
          }
        });
      </script>
    </body>
    </html>
  `;


    return (
        <View style={{ height: "100%", backgroundColor: "#F7F7F7" }}>
            <Stack.Screen
                options={{
                    headerShown: false
                }}
            />
            <NavBack
                title="空间"
                search={true}
                searchMethod={searchMethod}
            />

            <WebView originWhitelist={['*']} source={{ html }} style={{ flex: 1 }} ref={webviewRef}  />

            {/*<MapView*/}
            {/*    style={{ flex: 1 }}*/}
            {/*    region={{*/}
            {/*        latitude: lt,  // 默认显示北京*/}
            {/*        longitude: lg, // 默认显示北京*/}
            {/*        latitudeDelta: 0.02, // 更小的值可以更大程度地放大到县级*/}
            {/*        longitudeDelta: 0.02, // 尝试从更小的缩放级别开始*/}
            {/*    }}*/}
            {/*    zoomLevel={10}*/}
            {/*>*/}
            {/*    {*/}
            {/*        list?.map((location: any, idx: number) => {*/}
            {/*            console.log('location?.addressBackUp', location?.addressBackup);*/}
            {/*            if (location?.addressBackup?.count > 0) {*/}
            {/*                const address = location?.addressBackup?.data;*/}
            {/*                console.log('address', location?.addressBackup?.data[0].location);*/}
            {/*                return (*/}
            {/*                    <Marker*/}
            {/*                        key={idx}*/}
            {/*                        coordinate={{*/}
            {/*                            latitude: location?.addressBackup?.data[0].location?.lat,*/}
            {/*                            longitude: location?.addressBackup?.data[0].location?.lng,*/}
            {/*                        }}*/}
            {/*                        title={location?.addressBackup?.data[0]?.title}*/}
            {/*                        description={location?.addressBackup?.data[0]?.category}*/}
            {/*                        style={{ shadowOpacity: 0 }} // 禁用阴影*/}
            {/*                        image={mapIcon}*/}
            {/*                    >*/}
            {/*                        /!*<View style={styles.mapIcon}>*!/*/}
            {/*                        /!*    <Image source={mapIcon} style={{ width: "100%", height: "100%" }}/>*!/*/}
            {/*                        /!*</View>*!/*/}

            {/*                    </Marker>*/}
            {/*                )*/}
            {/*            };*/}
            {/*        })*/}
            {/*    }*/}
                {/*<Marker*/}
                {/*    coordinate={{*/}
                {/*        latitude: 23.114155,*/}
                {/*        longitude: 113.318977,*/}
                {/*    }}*/}
                {/*    title="北京"*/}
                {/*    description="天安门"*/}
                {/*/>*/}
            {/*</MapView>*/}
            <View style={styles.spaceContainer}>

                <Carousel
                    loop
                    data={list}
                    width={width * 0.8} // 每个 item 的宽度
                    height={200} // 每个 item 的高度
                    mode="parallax" // 视差模式
                    modeConfig={{
                        parallaxScrollingScale: 0.9, // 中间项目的缩放比例
                        parallaxScrollingOffset: 20, // 控制左右项目露出多少
                        parallaxAdjacentItemScale: 0.9, // 左右项目缩放比例
                    }}
                    customConfig={() => ({
                        type: 'positive',
                    })}
                    style={{
                        overflow: 'visible',
                        marginHorizontal: width * 0.05, // 确保左右 item 不被父容器裁剪
                    }}
                    renderItem={({ item , index}) => {
                        return (
                            <View
                                onStartShouldSetResponder={() => true} // 确保组件可以响应手势
                                onResponderGrant={(e) => {
                                    touchStartX.current = e.nativeEvent.pageX; // 记录触摸起点
                                    touchStartY.current = e.nativeEvent.pageY;
                                    isSliding.current = false; // 初始化滑动状态
                                }}
                                onResponderMove={handleResponderMove} // 检测滑动
                                onResponderRelease={(e) => handleResponderRelease(e, item)} // 处理释放手势
                            >
                                <View style={[styles.roomItem, { height: 150 }]} key={index}>
                                    <View style={styles.imgList}>
                                        {
                                            item?.imgUrl?.map((it: any, index: number) => {
                                                return (
                                                    <Image source={{ uri: it }} style={styles.imgItem}/>
                                                )
                                            })
                                        }
                                    </View>
                                    <View style={styles.roomTitle}>
                                        <Text style={styles.roomTitleText} numberOfLines={1}>{ item?.name }</Text>
                                    </View>
                                    <View style={styles.addressWrap}>
                                        <View style={styles.locationIcon}>
                                            <Image source={locationIcon} style={{ width: "100%", height: "100%" }}/>
                                        </View>

                                        <View style={[styles.addressContent, { width: 250 }]}>
                                            <Text style={styles.addressContentText}>
                                                { item?.addressBackup?.data?.length > 0 && item?.addressBackup?.data[0]?.address }
                                            </Text>
                                        </View>
                                    </View>
                                </View>
                            </View>
                        )
                    }}
                />

                {/*<View style={styles.roomList}>*/}
                {/*    <View style={styles.roomItem}>*/}
                {/*        <View style={styles.imgList}>*/}
                {/*            <Image source={demoImage} style={styles.imgItem}/>*/}
                {/*            <Image source={demoImage} style={styles.imgItem}/>*/}
                {/*            <Image source={demoImage} style={styles.imgItem}/>*/}
                {/*        </View>*/}
                {/*        <View style={styles.roomTitle}>*/}
                {/*            <Text style={styles.roomTitleText}>长乐🐟池</Text>*/}
                {/*        </View>*/}
                {/*        <View style={styles.addressWrap}>*/}
                {/*            <View style={styles.locationIcon}>*/}
                {/*                <Image source={locationIcon} style={{ width: "100%", height: "100%" }}/>*/}
                {/*            </View>*/}

                {/*            <View style={styles.addressContent}>*/}
                {/*                <Text style={styles.addressContentText}>天源路5号(地铁3.6号线天河客运站A.D出口)</Text>*/}
                {/*            </View>*/}
                {/*        </View>*/}
                {/*    </View>*/}
                {/*    <View style={styles.roomItem}>*/}
                {/*        <View style={styles.imgList}>*/}
                {/*            <Image source={demoImage} style={styles.imgItem}/>*/}
                {/*            <Image source={demoImage} style={styles.imgItem}/>*/}
                {/*            <Image source={demoImage} style={styles.imgItem}/>*/}
                {/*        </View>*/}
                {/*        <View style={styles.roomTitle}>*/}
                {/*            <Text style={styles.roomTitleText}>长乐🐟池</Text>*/}
                {/*        </View>*/}
                {/*        <View style={styles.addressWrap}>*/}
                {/*            <View style={styles.locationIcon}>*/}
                {/*                <Image source={locationIcon} style={{ width: "100%", height: "100%" }}/>*/}
                {/*            </View>*/}

                {/*            <View style={styles.addressContent}>*/}
                {/*                <Text style={styles.addressContentText}>天源路5号(地铁3.6号线天河客运站A.D出口)</Text>*/}
                {/*            </View>*/}
                {/*        </View>*/}
                {/*    </View>*/}
                {/*    <View style={styles.roomItem}>*/}
                {/*        <View style={styles.imgList}>*/}
                {/*            <Image source={demoImage} style={styles.imgItem}/>*/}
                {/*            <Image source={demoImage} style={styles.imgItem}/>*/}
                {/*            <Image source={demoImage} style={styles.imgItem}/>*/}
                {/*        </View>*/}
                {/*        <View style={styles.roomTitle}>*/}
                {/*            <Text style={styles.roomTitleText}>长乐🐟池</Text>*/}
                {/*        </View>*/}
                {/*        <View style={styles.addressWrap}>*/}
                {/*            <View style={styles.locationIcon}>*/}
                {/*                <Image source={locationIcon} style={{ width: "100%", height: "100%" }}/>*/}
                {/*            </View>*/}

                {/*            <View style={styles.addressContent}>*/}
                {/*                <Text style={styles.addressContentText}>天源路5号(地铁3.6号线天河客运站A.D出口)</Text>*/}
                {/*            </View>*/}
                {/*        </View>*/}
                {/*    </View>*/}
                {/*    <View style={styles.roomItem}>*/}
                {/*        <View style={styles.imgList}>*/}
                {/*            <Image source={demoImage} style={styles.imgItem}/>*/}
                {/*            <Image source={demoImage} style={styles.imgItem}/>*/}
                {/*            <Image source={demoImage} style={styles.imgItem}/>*/}
                {/*        </View>*/}
                {/*        <View style={styles.roomTitle}>*/}
                {/*            <Text style={styles.roomTitleText}>长乐🐟池</Text>*/}
                {/*        </View>*/}
                {/*        <View style={styles.addressWrap}>*/}
                {/*            <View style={styles.locationIcon}>*/}
                {/*                <Image source={locationIcon} style={{ width: "100%", height: "100%" }}/>*/}
                {/*            </View>*/}

                {/*            <View style={styles.addressContent}>*/}
                {/*                <Text style={styles.addressContentText}>天源路5号(地铁3.6号线天河客运站A.D出口)</Text>*/}
                {/*            </View>*/}
                {/*        </View>*/}
                {/*    </View>*/}
                {/*</View>*/}

            </View>
        </View>

    );
}

const styles = StyleSheet.create({
    spaceContainer: {
        position: "absolute",
        bottom: 0,
    },
    roomItem: {
        backgroundColor: "#fff",
        padding: 12,
        marginLeft: 12,
        borderRadius: 6,
        width: "100%",
    },
    imgList: {
        flexDirection: "row",
    },
    imgItem: {
        width: 95,
        height: 58,
        borderRadius: 6,
        marginRight: 3,
    },
    roomTitle: {
        marginTop: 10,
    },
    roomTitleText: {
        fontSize: 16,
        fontWeight: "bold",
    },
    locationIcon: {
        width: 14,
        height: 14,
        marginRight: 6,
    },
    addressWrap: {
        flexDirection: "row",
        alignItems: "center",
        marginTop: 5,
    },
    addressContent: {

    },
    addressContentText: {
        fontSize: 14,
        color: "#676978"
    },
    roomList: {
        flexDirection: "row",
        overflow: "scroll",
        width: "100%"
    },
    slide: {
        flex: 1,
        alignItems: 'center',
        justifyContent: 'center',
    },
    imageContainer: {
        width: '90%',
        height: 200,
        overflow: 'hidden',
        borderRadius: 15,
    },
    image: {
        width: '100%',
        height: '100%',
        resizeMode: 'cover',
    },
    text: {
        marginTop: 10,
        fontSize: 16,
        fontWeight: 'bold',
    },
    mapIcon: {
        width: 40,
        height: 40,
        resizeMode: "contain"
    },
});
